package com.bocaizp.operation.webSocket;


import com.alibaba.fastjson2.JSON;
import com.bocaizp.common.utils.MessageUtils;
import com.bocaizp.operation.mapper.ChatMapper;
import com.bocaizp.operation.service.ChatService;
import com.bocaizp.operation.webSocket.pojo.Message;
import com.bocaizp.pojo.VO.FriendListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @version v1.0
 * @ClassName: ChatEndpoint
 * @Description: TODO(一句话描述该类的功能)
 * @Author: 黑马程序员
 */
@ServerEndpoint(value = "/user/chat/{sid}")
@Component
@Slf4j
public class ChatEndpoint {

    private static final Map<String,Session> onlineUsers = new ConcurrentHashMap<>();

    private String sid;

    //
    private static ChatService chatService;

    @Autowired
    public void setChatService(ChatService chatService) {
        ChatEndpoint.chatService = chatService;
    }


    /**
     * 建立websocket连接后，被调用
     * @param session
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid) {
        //1，将session进行保存
        this.sid = sid;
        onlineUsers.put(sid,session);
        //2，广播消息。需要将登陆的所有的用户推送给所有的用户
        int flag = -1;
        String message = MessageUtils.getMessage(true,null,getFriends(), flag);
        broadcastAllUsers(message);
    }

    public Set getFriends() {
		return onlineUsers.keySet();
    }

    private void broadcastAllUsers(String message) {
        try {
            //遍历map集合
            Set<Map.Entry<String, Session>> entries = onlineUsers.entrySet();
            for (Map.Entry<String, Session> entry : entries) {
                //获取到所有用户对应的session对象
                Session session = entry.getValue();
                //发送消息
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            //记录日志
        }
    }



    /**
     * 浏览器发送消息到服务端，该方法被调用
     *
     * 张三  -->  李四
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {

        try {
            //将消息推送给指定的用户
            Message msg = JSON.parseObject(message, Message.class);
            //获取 消息接收方的用户id
            String toName = msg.getToName();
            String mess = msg.getMessage();
            int flag = msg.getFlag();
            log.info("开始存入聊天记录...");
            chatService.insertRecord(sid, toName, mess, flag);

            log.info("完成存入聊天记录");
            //获取消息接收方用户对象的session对象
            Session session = onlineUsers.get(toName);

            String msg1 = MessageUtils.getMessage(false, sid, mess, flag);

            session.getBasicRemote().sendText(msg1);

        } catch (Exception e) {
            //记录日志
        }
    }

    /**
     * 断开 websocket 连接时被调用
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        //1,从onlineUsers中剔除当前用户的session对象

        onlineUsers.remove(sid);
        //2,通知其他所有的用户，当前用户下线了
        int flag = -1;
        String message = MessageUtils.getMessage(true,null,getFriends(), flag);
        broadcastAllUsers(message);
    }
}
